package com.czmh.etc.onlinepubsys.controller.cmg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.common.core.utils.Base64ImageUtil;
import com.czmh.etc.onlinepubsys.constants.cmg.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.enums.cmg.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.request.cmg.*;
import com.czmh.etc.onlinepubsys.response.cmg.ApiResponseBase;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcOrderService;
import com.czmh.etc.onlinepubsys.utils.ImageZipUtil;
import com.czmh.etc.onlinepubsys.utils.cmg.CmgHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.czmh.etc.common.core.utils.Base64ImageUtil;

@Slf4j
@RestController
@RequestMapping("/{version}/api/cmg/newApply")
@Api(tags = "申办卡签接口相关（新）")
public class NewCmgApplyController {
    @Value("${newcmg.toAccessNo}")
    private String toAccessno;

    @Value("${newcmg.authAccessNo}")
    private String authAccessNo;

    @Autowired
    private EtcOrderService etcOrderServicee;
    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;
    @Autowired
    private EtcOrderService orderService;
    @Autowired
    private IEtcOrderService etcOrderService;
    @Autowired
    private ICurrentContextService currentContextService;

    @PostMapping("/addCustomerInfo")
    @ApiOperation("预录入ETC客户信息")
    public JSONResult addCustomerInfo(@RequestBody NewAddCustomerInfoRequest req) {
        JSONResult result = new JSONResult();
        log.info("addCustomerInfo:{}", JSON.toJSONString(req));
        //判断是否继续申办
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext != null && currentContext.getState() == 0) {
            //录入数据库
            String jsonStr = currentContext.getJsonData();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            jsonObject.put("etcApplyRequest", req);
            currentContext.setJsonData(jsonObject.toJSONString());
            currentContextService.update(currentContext);
        }
        //请求招商
        Long time = System.currentTimeMillis();
        req.setToAuthAccessNo(authAccessNo);
        req.setTime(time);
        req.setName(req.getAccountName());
        if(req.getIdType() == 5){
            req.setPicData(Base64ImageUtil.imgToBase64(req.getCertImg()));
        }
        if (req.getIdType() == 0) {
            req.setPicData(Base64ImageUtil.imgToBase64(req.getAgentFrontImg()));
            req.setPicData2(Base64ImageUtil.imgToBase64(req.getAgentBackImg()));
        }
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.CUSTOMER_PREADD, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            log.info("CUSTOMER_PREADD:{}", JSON.toJSONString(r));
            result.setRspData(r.getCode());
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        } else {
            result.setCode(r != null ? r.getCode() : com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage(r.getMsg());
        }
        return result;
    }

    @PostMapping("/addAgent")
    @ApiOperation("预录入经办人信息")
    public JSONResult addAgent(@RequestBody NewAddAgentRequest req) {
        JSONResult result = new JSONResult();
        log.info("addAgent:{}", JSON.toJSONString(req));
        //判断是否继续申办
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext != null && currentContext.getState() == 0) {
            //录入数据库
            String jsonStr = currentContext.getJsonData();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            jsonObject.put("addAgentRequest", req);
            currentContext.setJsonData(jsonObject.toJSONString());
            currentContextService.update(currentContext);
        }
        //请求招商
        Long time = System.currentTimeMillis();
        req.setToAuthAccessNo(authAccessNo);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.AGENT_PREADD, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            log.info("AGENT_PREADD:{}", JSON.toJSONString(r));
            result.setRspData(r.getCode());
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        } else {
            result.setCode(r != null ? r.getCode() : com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage(r.getMsg());
        }
        return result;
    }

    @PostMapping("/addVehicle")
    @ApiOperation("预录入车辆信息接口")
    public JSONResult addVehicle(@RequestBody NewAddVehicleRequest req) {
        JSONResult result = new JSONResult();
        log.info("addVehicle:{}", JSON.toJSONString(req));
        //请求招商
        Long time = System.currentTimeMillis();
        req.setToAuthAccessNo(authAccessNo);
        req.setTime(time);
        req.setPicData(Base64ImageUtil.imgToBase64(req.getVehCertFrontImg()));
        req.setPicData2(Base64ImageUtil.imgToBase64(req.getVehCertBackImg()));
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.VEHICLE_PREADD, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            log.info("VEHICLE_PREADD:{}", JSON.toJSONString(r));
            result.setRspData(r.getCode());
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        } else {
            result.setCode(r != null ? r.getCode() : com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage(r.getMsg());
        }
        return result;
    }

    @PostMapping("/cancelBusiness")
    @ApiOperation("申办业务单取消接口")
    public JSONResult cancelBusiness(@RequestBody NewCancelBusinessRequest req) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(req.getOrderNo())) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        EtcOrder etcOrder = etcOrderService.getByOrderNo(req.getOrderNo());
        if (etcOrder == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("订单不存在");
        }
        //判断产品编码对应的用户流程是否存在
        CurrentContext currentContext = currentContextService.getByUserId(etcOrder.getUserId());
        if (currentContext == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("用户不在流程当中");
            return result;
        }
        log.info("cancelBusiness:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_CANCEL_BUSINESS, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            //取消订单成功之后逻辑删除流程并物理删除订单
            result.setRspData(r.getBizContent());
            result.setMessage(r.getMsg());
            currentContext.setState(6);
            currentContext.setDeleteFlag(1);
            currentContextService.update(currentContext);
            EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
            log.info("招行取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
            log.info("招行取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
            log.info("招行取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
            etcOrder.setPayState(3);
            etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
            orderService.updateById(etcOrder);
            etcUser.setUser_loginname("");
            etcUser.setUser_phone("");
            etcUserInfoSevice.updateUser(etcUser);
        } else if (r.getCode().equalsIgnoreCase("ORDER_NOT_FOUND")) {
            //取消订单成功之后逻辑删除流程并物理删除订单
            result.setRspData(r.getBizContent());
            result.setMessage(r.getMsg());
            currentContext.setState(6);
            currentContext.setDeleteFlag(1);
            currentContextService.update(currentContext);
            EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
            log.info("招行取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
            log.info("招行取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
            log.info("招行取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
            etcOrder.setPayState(3);
            etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
            orderService.updateById(etcOrder);
            etcUser.setUser_loginname("");
            etcUser.setUser_phone("");
            etcUserInfoSevice.updateUser(etcUser);
        } else {
            result.setCode(r != null ? r.getCode() : com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage(r.getMsg());
        }
        return result;
    }
}
